local extension = Package("rbjdingjue")
extension.extensionName = "rbaijiang"
extension.game_modes_whitelist = { "m_3v3_mode" }
local m_3v3_mode = Fk.game_modes["m_3v3_mode"]
table.insertTable(m_3v3_mode.whitelist, {"rbjdingjue"})

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["rbaijiang"] = "拜将",
  ["rbj"] = "拜将",
  ["rbjdingjue"] = "定爵",
}

local rbaijiang_rule = fk.CreateTriggerSkill{
  name = "#rbaijiang_rule",
  priority = 0.001,
  global = true,

  refresh_events = {fk.GamePrepared},
  can_refresh = function(self, event, target, player, data)
    return player.room.settings.gameMode == "m_3v3_mode" and
      not table.every({"rbjdingjue", "rbjtianzi"}, function (p)
        return table.contains(player.room.disabled_packs, p)
      end)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.players) do
      for _, q in ipairs(room.players) do
        if p ~= q and p.role[1] == q.role[1] then
          p:addBuddy(q)
        end
      end
    end
  end,
}
Fk:addSkill(rbaijiang_rule)

local zhangyiy = General(extension, "rbj__zhangyiy", "shu", 4)
local rbj__guwang = fk.CreateTriggerSkill{
  name = "rbj__guwang",
  anim_type = "offensive",
  events = {fk.CardUsing, fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.CardUsing then
        return data.card.trueName == "slash" and not player.chained
      elseif event == fk.DamageInflicted then
        return player.chained or not player.faceup or player:getMark("@!action-round") > 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return player.room:askForSkillInvoke(player, self.name, nil, "#rbj__guwang-invoke:::"..data.card:toLogString())
    elseif event == fk.DamageInflicted then
      local choices = {}
      if player.chained or not player.faceup then
        table.insert(choices, "rbj__guwang_reset")
      end
      if player:getMark("@!action-round") > 0 then
        table.insert(choices, "rbj__guwang_action")
      end
      table.insert(choices, "Cancel")
      local choice = player.room:askForChoice(player, choices, self.name,
        "#rbj__guwang-choice", false, {"rbj__guwang_reset", "rbj__guwang_action", "Cancel"})
      if choice ~= "Cancel" then
        self.cost_data = choice
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.CardUsing then
      player:setChainState(true)
      data.additionalEffect = (data.additionalEffect or 0) + 1
    elseif event == fk.DamageInflicted then
      data.damage = data.damage + 1
      if self.cost_data[13] == "r" then
        player:reset()
      else
        player.room:setPlayerMark(player, "@!action-round", 0)
      end
    end
  end,
}
zhangyiy:addSkill(rbj__guwang)
Fk:loadTranslationTable{
  ["rbj__zhangyiy"] = "张翼",
  ["#rbj__zhangyiy"] = "佑序有炎",
  ["designer:rbj__zhangyiy"] = "三秋",
  ["illustrator:rbj__zhangyiy"] = "鬼画府",

  ["rbj__guwang"] = "孤往",
  [":rbj__guwang"] = "当你使用【杀】时，你可以横置武将牌，令此牌额外结算一次；当你受到伤害时，你可以令此伤害+1，然后重置武将牌或身份牌。",
  ["#rbj__guwang-invoke"] = "孤往：是否横置武将牌，令此%arg额外结算一次？",
  ["#rbj__guwang-choice"] = "孤往：是否令你受到的伤害+1，重置武将牌或身份牌？",
  ["rbj__guwang_reset"] = "重置武将牌",
  ["rbj__guwang_action"] = "重置身份牌",
}

local caoren = General(extension, "rbj__caoren", "wei", 4)
local rbj__congming = fk.CreateViewAsSkill{
  name = "rbj__congming",
  anim_type = "control",
  pattern = "nullification",
  prompt = function ()
    return "#rbj__congming::"..Self:getMark("rbj__congming_to")
  end,
  expand_pile = function(self)
    return Self:getTableMark("rbj__congming_cards")
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      if Self:getMark("rbj__congming_to") == Self.id then
        return table.contains(Self:getCardIds("h"), to_select)
      else
        return table.contains(Self:getTableMark("rbj__congming_cards"), to_select)
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  before_use = function (self, player, use)
    if player:getMark("rbj__congming_to") == player.id or
      Fk:getCardById(use.card.subcards[1]).type == Card.TypeBasic then
      use.extra_data = use.extra_data or {}
      use.extra_data.rbj__congming = true
    end
  end,
  after_use = function (self, player, use)
    local room = player.room
    if use.extra_data and use.extra_data.rbj__congming then
      if use.toCard and room:getCardArea(use.toCard) == Card.Processing and not player.dead then
        room:moveCardTo(use.toCard, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
      end
    end
  end,
  enabled_at_response = function (self, player, response)
    if not response then
      local room = Fk:currentRoom()
      local to = nil
      player:setMark("rbj__congming_to", 0)
      player:setMark("rbj__congming_cards", 0)
      local friends = table.filter(room.alive_players, function (p)
        return p.role[1] == player.role[1]
      end)
      if #friends == 1 then
        if not friends[1]:isKongcheng() then
          to = friends[1]
        end
      else
        local nums = {}
        for _, p in ipairs(friends) do
          table.insertIfNeed(nums, p:getHandcardNum())
        end
        if #nums == #friends then
          local n = math.max(table.unpack(nums))
          to = table.find(friends, function (p)
            return p:getHandcardNum() == n
          end)
        end
      end
      if to then
        player:setMark("rbj__congming_to", to.id)
        if to ~= player then
          player:setMark("rbj__congming_cards", to:getCardIds("h"))
        end
      end
      return player:getMark("rbj__congming_to") ~= 0
    end
  end,
}
caoren:addSkill(rbj__congming)
Fk:loadTranslationTable{
  ["rbj__caoren"] = "曹仁",
  ["#rbj__caoren"] = "千嶂边城",
  ["designer:rbj__caoren"] = "三秋",
  ["illustrator:rbj__caoren"] = "君桓文化",

  ["rbj__congming"] = "琮铭",
  [":rbj__congming"] = "当你需使用【无懈可击】时，若所有友方角色手牌数均不同，你可以将手牌数最多的友方角色的一张手牌当【无懈可击】使用；"..
  "若为你或此牌为基本牌，你获得此【无懈可击】抵消的牌。",
  ["#rbj__congming"] = "琮铭：你可以将 %dest 的一张手牌当【无懈可击】使用",
}

local gongsunzan = General(extension, "rbj__gongsunzan", "qun", 4)
local rbj__dengcheng = fk.CreateTriggerSkill{
  name = "rbj__dengcheng",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target.phase == Player.Start and not target.dead and not target:isNude() then
      local room = player.room
      if room.logic.event_recorder[GameEvent.Turn] then
        local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
        local turn_events = room.logic.event_recorder[GameEvent.Turn]
        local last = nil
        if turn_event then
          if #turn_events > 1 then
            last = turn_events[#turn_events - 1].data[1]
          end
        else
          last = turn_events[#turn_events].data[1]
        end
        if last ~= nil and last.role[1] == target.role[1] then
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat
    if player:isBuddy(target) or target:isKongcheng() then
      local cards = target:getCardIds("he")
      room:setPlayerMark(player, "rbj__dengcheng-tmp", cards)
      if target == player then
        cards = {}
      end
      success, dat = player.room:askForUseActiveSkill(player, "rbj__dengcheng_active",
        "#rbj__dengcheng-invoke::"..target.id, true, {bypass_times = true, expand_pile = cards})
      room:setPlayerMark(player, "rbj__dengcheng-tmp", 0)
    elseif room:askForSkillInvoke(player, self.name, nil, "#rbj__dengcheng-invoke::"..target.id) then
      local card = room:askForCardChosen(player, target, "he", self.name, "#rbj__dengcheng-choose::"..target.id)
      dat = U.askForUseVirtualCard(room, player, "slash", nil, self.name,
        "#rbj__dengcheng-use", true, true, false, true, nil, true)
      if dat then
        success = true
        local new_dat = {
          cards = {card},
          targets = TargetGroup:getRealTargets(dat.tos),
        }
        dat = new_dat
      end
    end
    if success and dat then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk:cloneCard("slash")
    card:addSubcards(self.cost_data.cards)
    card.skillName = self.name
    local use = {
      from = player.id,
      tos = table.map(self.cost_data.targets, function(id) return {id} end),
      card = card,
      extraUse = true,
    }
    if player:getMark("@!action-round") == 0 and
      room:askForSkillInvoke(player, self.name, nil, "#rbj__dengcheng-action") then
      room:setPlayerMark(player, "@!action-round", 1)
      use.additionalDamage = (use.additionalDamage or 0) + 1
    end
    room:useCard(use)
  end,
}
local rbj__dengcheng_active = fk.CreateViewAsSkill{
  name = "rbj__dengcheng_active",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and table.contains(Self:getMark("rbj__dengcheng-tmp"), to_select)
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card:addSubcards(cards)
    return card
  end,
}
Fk:addSkill(rbj__dengcheng_active)
gongsunzan:addSkill(rbj__dengcheng)
Fk:loadTranslationTable{
  ["rbj__gongsunzan"] = "公孙瓒",
  ["#rbj__gongsunzan"] = "镗岩无射",
  ["designer:rbj__gongsunzan"] = "三秋",
  ["illustrator:rbj__gongsunzan"] = "fingerling",

  ["rbj__dengcheng"] = "镫骋",
  [":rbj__dengcheng"] = "一名角色的准备阶段，若上一名执行回合的角色与该角色阵营相同，你可以将该角色的一张牌当【杀】使用，使用前你可以横置"..
  "身份牌，令此牌伤害+1。",
  ["#rbj__dengcheng-invoke"] = "镫骋：是否将 %dest 的一张牌当【杀】使用？",
  ["#rbj__dengcheng-choose"] = "镫骋：选择 %dest 的一张牌",
  ["#rbj__dengcheng-use"] = "镫骋：选择此【杀】的目标",
  ["#rbj__dengcheng-action"] = "镫骋：是否横置身份牌，令此牌伤害+1？",
  ["rbj__dengcheng_active"] = "镫骋",
}

local zhuran = General(extension, "rbj__zhuran", "wu", 4)
local rbj__qingyu = fk.CreateTriggerSkill{
  name = "rbj__qingyu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and
      player:getHandcardNum() < player:getMaxCards()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player:drawCards(player:getMaxCards() - player:getHandcardNum(), self.name)
    if player.dead then return end
    if not table.find(room:getOtherPlayers(player), function (p)
      return p.role[1] == player.role[1]
    end) then
      cards = table.filter(cards, function (id)
        return table.contains(player:getCardIds("h"), id)
      end)
      if #cards == 0 then return end
      if room:askForSkillInvoke(player, self.name, nil, "#rbj__qingyu-invoke") then
        for _, id in ipairs(cards) do
          room:setCardMark(Fk:getCardById(id), "@@rbj__qingyu-inhand", 1)
        end
      end
    end
  end,

  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function (self, event, target, player, data)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) > 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(player:getCardIds("h")) do
      room:setCardMark(Fk:getCardById(id), "@@rbj__qingyu-inhand", 0)
    end
  end,
}
local rbj__qingyu_filter = fk.CreateFilterSkill{
  name = "#rbj__qingyu_filter",
  card_filter = function(self, card, player)
    return card:getMark("@@rbj__qingyu-inhand") > 0 and table.contains(player:getCardIds("h"), card.id)
  end,
  view_as = function(self, card)
    return Fk:cloneCard("slash", card.suit, card.number)
  end,
}
rbj__qingyu:addRelatedSkill(rbj__qingyu_filter)
zhuran:addSkill(rbj__qingyu)
Fk:loadTranslationTable{
  ["rbj__zhuran"] = "朱然",
  ["#rbj__zhuran"] = "江陵霜天",
  ["designer:rbj__zhuran"] = "三秋",
  ["illustrator:rbj__zhuran"] = "秋呆呆",

  ["rbj__qingyu"] = "清御",
  [":rbj__qingyu"] = "锁定技，当你使用【杀】后，你将手牌摸至手牌上限。孤军：然后你可以令因此获得的牌视为【杀】直到回合结束。",
  ["#rbj__qingyu-invoke"] = "清御：是否令这些牌本回合视为【杀】？",
  ["@@rbj__qingyu-inhand"] = "清御",
  ["#rbj__qingyu_filter"] = "清御",
}

local zhugeke = General(extension, "rbj__zhugeke", "wu", 3)
local rbj__minliu = fk.CreateViewAsSkill{
  name = "rbj__minliu",
  pattern = ".|.|.|.|.|basic",
  prompt = function ()
    return "#rbj__minliu"
  end,
  interaction = function()
    local names = {}
    local mark = U.getMark(Self, "rbj__minliu-round")
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if ((Fk.currentResponsePattern == nil and Self:canUse(card)) or
      (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card))) then
        if card.type == Card.TypeBasic and not table.contains(mark, card.trueName) then
          table.insertIfNeed(names, card.name)
        end
      end
    end
    if #names == 0 then return false end
    return UI.ComboBox {choices = names}
  end,
  view_as = function(self, cards)
    if not self.interaction.data  then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    if room.logic:getCurrentEvent():findParent(GameEvent.Round) and
      #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local u = e.data[1]
        if u.card.trueName == use.card.trueName and room:getPlayerById(u.from).role[1] ~= player.role[1] then
          return true
        end
      end, Player.HistoryRound) == 0 then
      player:drawCards(1, self.name)
    end
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}
local rbj__minliu_trigger = fk.CreateTriggerSkill{
  name = "#rbj__minliu_trigger",

  refresh_events = {fk.AfterCardUseDeclared, fk.EventAcquireSkill, fk.RoundEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardUseDeclared then
      return player:hasSkill("rbj__minliu", true) and target.role[1] == player.role[1]
    elseif event == fk.EventAcquireSkill then
      return target == player and data == rbj__minliu and player.room:getTag("RoundCount")
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardUseDeclared then
      room:addTableMark(player, "rbj__minliu-round", data.card.trueName)
    elseif event == fk.EventAcquireSkill then
      if room.logic:getCurrentEvent():findParent(GameEvent.Round) then
        local names = {}
        room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
          local use = e.data[1]
          if room:getPlayerById(use.from).role[1] == player.role[1] then
            table.insertIfNeed(names, use.card.trueName)
          end
          return false
        end, Player.HistoryRound)
        room:setPlayerMark(player, "rbj__minliu-round", names)
      end
    end
  end,
}
local rbj__quyue = fk.CreateTriggerSkill{
  name = "rbj__quyue",
  events = {fk.BeforeDrawCard},
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMaxCards() > 0
  end,
  on_cost = function(self, event, target, player, data)
    player.room:askForSkillInvoke(player, self.name, nil, "#rbj__quyue-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.num = data.num + 1
    room:addPlayerMark(player, "@rbj__quyue-turn", 1)
    room:addPlayerMark(player, MarkEnum.MinusMaxCardsInTurn, 1)
    room:broadcastProperty(player, "MaxCards")
  end,

  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@rbj__quyue-turn") > 0 and
      #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.from == player.id and move.moveReason == fk.ReasonDiscard then
            return true
          end
        end
      end, Player.HistoryTurn) > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, MarkEnum.MinusMaxCards, player:getMark("@rbj__quyue-turn"))
    room:removePlayerMark(player, MarkEnum.MinusMaxCardsInTurn, player:getMark("@rbj__quyue-turn"))
    room:broadcastProperty(player, "MaxCards")
  end,
}
rbj__minliu:addRelatedSkill(rbj__minliu_trigger)
zhugeke:addSkill(rbj__minliu)
zhugeke:addSkill(rbj__quyue)
Fk:loadTranslationTable{
  ["rbj__zhugeke"] = "诸葛恪",
  ["#rbj__zhugeke"] = "才斐勘难",
  ["designer:rbj__zhugeke"] = "三秋",
  ["illustrator:rbj__zhugeke"] = "鬼画府",

  ["rbj__minliu"] = "敏流",
  [":rbj__minliu"] = "你可以视为使用友方角色本轮未使用过的基本牌；若本轮敌方角色也未使用过，你摸一张牌。",
  ["rbj__quyue"] = "趋越",
  [":rbj__quyue"] = "当你摸牌时，你可以令本回合你手牌上限-1，令本次摸牌数+1；回合结束时，若你本回合弃置过牌，你本回合因此减少的手牌上限不复原。",
  ["#rbj__minliu"] = "敏流：你可以视为使用友方角色本轮未使用过的基本牌",
  ["#rbj__quyue-invoke"] = "趋越：是否额外摸一张牌，本回合你手牌上限-1？",
  ["@rbj__quyue-turn"] = "趋越",
}

local xingcai = General(extension, "rbj__xingcai", "shu", 4, 4, General.Female)
local rbj__xianyi = fk.CreateViewAsSkill{
  name = "rbj__xianyi",
  pattern = "slash",
  prompt = "#rbj__xianyi",
  expand_pile = function () return Self:getTableMark("rbj__xianyi_discard-turn") end,
  card_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and table.contains(Self:getMark("rbj__xianyi_discard-turn"), to_select)
  end,
  view_as = function(self, cards)
    return Fk:getCardById(cards[1])
  end,
  before_use = function(self, player, use)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p) return p.role[1] == player.role[1] and #p:getCardIds("ej") > 0 end)
    if #targets == 0 then return "" end
    use.extraUse = true
    if not table.contains(player:getTableMark("rbj__xianyi_leaveme-turn"), use.card.id) then
      use.extra_data = use.extra_data or {}
      use.extra_data.rbj__xianyiGet = player.id
    end

    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#rbj__xianyi-choose", self.name, false)
    local to = room:getPlayerById(tos[1])
    local cid = room:askForCardChosen(player, to, "ej", self.name)
    room:obtainCard(player, cid, true, fk.ReasonJustMove, player.id, self.name)
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
      table.find(Fk:currentRoom().alive_players, function(p)
        return p.role[1] == player.role[1] and #p:getCardIds("ej") > 0
      end)
  end,
  enabled_at_response = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
      table.find(Fk:currentRoom().alive_players, function(p)
        return p.role[1] == player.role[1] and #p:getCardIds("ej") > 0
      end)
  end,
}

local rbj__xianyi_trigger = fk.CreateTriggerSkill{
  name = "#rbj__xianyi_trigger",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return not player.dead and (data.extra_data or {}).rbj__xianyiGet == player.id
    and player.room:getCardArea(data.card) == Card.Processing
  end,
  on_cost = Util.TrueFunc,
  on_use= function (self, event, target, player, data)
    player.room:obtainCard(player, data.card, true, fk.ReasonJustMove, player.id, self.name)
  end,

  refresh_events = {fk.AfterCardsMove, fk.EventAcquireSkill, fk.AfterDrawPileShuffle},
  can_refresh = function(self, event, target, player, data)
    if not player:hasSkill(rbj__xianyi, true) then return false end
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.from == player.id or move.toArea == Card.DiscardPile or move.fromArea == Card.DiscardPile then
          return true
        end
      end
    elseif event == fk.EventAcquireSkill then
      return target == player and data == rbj__xianyi
    else
      return true
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.AfterDrawPileShuffle then
      room:setPlayerMark(player, "rbj__xianyi_discard-turn", {})
      return
    end
    local record_data = {}
    if event == fk.AfterCardsMove then
      record_data = {data}
    else
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        table.insert(record_data, e.data)
        return false
      end, Player.HistoryTurn)
    end
    local leaveMe = player:getTableMark("rbj__xianyi_leaveme-turn")
    local inDiscard = player:getTableMark("rbj__xianyi_discard-turn")
    for _, _data in ipairs(record_data) do
      for _, move in ipairs(_data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).trueName == "slash"
            and (info.fromArea == Player.Hand or info.fromArea == Player.Equip) then
              table.insertIfNeed(leaveMe, info.cardId)
            end
          end
        end
        if move.fromArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).trueName == "slash"  then
              table.removeOne(inDiscard, info.cardId)
            end
          end
        elseif move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).trueName == "slash"  then
              table.insert(inDiscard, info.cardId)
            end
          end
        end
      end
    end
    room:addTableMark(player, "rbj__xianyi_leaveme-turn", leaveMe)
    room:setPlayerMark(player, "rbj__xianyi_discard-turn", inDiscard)
  end,
}
rbj__xianyi:addRelatedSkill(rbj__xianyi_trigger)

-- 存在隐患
local rbj__xianyi_targetmod = fk.CreateTargetModSkill{
  name = "#rbj__xianyi_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return card and table.contains(player:getMark("rbj__xianyi_discard-turn"), card.id)
  end,
}
rbj__xianyi:addRelatedSkill(rbj__xianyi_targetmod)

xingcai:addSkill(rbj__xianyi)
Fk:loadTranslationTable{
  ["rbj__xingcai"] = "张星彩",
  ["#rbj__xingcai"] = "眉案钦锋",
  ["designer:rbj__xingcai"] = "三秋",
  ["illustrator:rbj__xingcai"] = "M云涯",

  ["rbj__xianyi"] = "贤熠",
  [":rbj__xianyi"] = "每回合限一次，当你需使用或打出【杀】时，你可以获得一名友方角色场上的一张牌，使用或打出一张本回合进入弃牌堆的【杀】，"..
  "以此法使用的【杀】无次数限制；若你本回合未失去过此【杀】，你获得之。",
  ["#rbj__xianyi"] = "贤熠：你可以获得友方角色场上的一张牌，以使用或打出本回合进入弃牌堆的【杀】",
  ["#rbj__xianyi-choose"] = "贤熠：获得一名友方角色场上的一张牌",
  ["#rbj__xianyi_trigger"] = "贤熠",
}

local shenpei = General(extension, "rbj__shenpei", "qun", 3)
local rbj__beiqu = fk.CreateTriggerSkill{
  name = "rbj__beiqu",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      table.find(player.room:getOtherPlayers(player), function (p)
        return p.role[1] == player.role[1] and player:canPindian(p)
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player), function (p)
      return p.role[1] == player.role[1] and player:canPindian(p)
    end)
    local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
      "#rbj__beiqu-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    local pindian = player:pindian({to}, self.name)
    if player.dead then return end
    local card
    if pindian.results[to.id].winner == player then
      card = pindian.fromCard
    elseif pindian.results[to.id].winner == to then
      card = pindian.results[to.id].toCard
    end
    if card and room:getCardArea(card) == Card.DiscardPile then
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
    if not player.dead and not to.dead and not player:isKongcheng() then
      U.askForUseRealCard(room, to, player:getCardIds("h"), nil, self.name,
        "#rbj__beiqu-use:"..player.id, {bypass_times = true, extraUse = true, expand_pile = player:getCardIds("h")}, false, true)
    end
  end,
}
local rbj__shuozu = fk.CreateTriggerSkill{
  name = "rbj__shuozu",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, self.name, player:getCardIds("h"))
    for _, id in ipairs(player:getCardIds("h")) do
      room:setCardMark(Fk:getCardById(id), "@@rbj__shuozu", 1)
    end
    player:filterHandcards()
  end,

  refresh_events = {fk.EventPhaseEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player.phase == Player.Play and player:getMark(self.name) ~= 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(player:getMark(self.name)) do
      room:setCardMark(Fk:getCardById(id), "@@rbj__shuozu", 0)
    end
    room:setPlayerMark(player, self.name, 0)
  end,
}
local rbj__shuozu_filter = fk.CreateFilterSkill{
  name = "#rbj__shuozu_filter",
  card_filter = function(self, card, player)
    return card:getMark("@@rbj__shuozu") > 0
  end,
  view_as = function(self, card)
    return Fk:cloneCard("archery_attack", card.suit, card.number)
  end,
}
rbj__shuozu:addRelatedSkill(rbj__shuozu_filter)
shenpei:addSkill(rbj__beiqu)
shenpei:addSkill(rbj__shuozu)
Fk:loadTranslationTable{
  ["rbj__shenpei"] = "审配",
  ["#rbj__shenpei"] = "崛城百战",
  ["designer:rbj__shenpei"] = "三秋",
  ["illustrator:rbj__shenpei"] = "YanBai",

  ["rbj__beiqu"] = "北趋",
  [":rbj__beiqu"] = "当你受到伤害后，你可以与一名友方角色拼点，你获得赢的角色的拼点牌，然后其可以使用你的一张手牌。",
  ["rbj__shuozu"] = "铄镞",
  [":rbj__shuozu"] = "锁定技，结束阶段，你此时手牌中的牌均视为【万箭齐发】直到你下个出牌阶段结束。",
  ["#rbj__beiqu-choose"] = "北趋：你可以与一名友方角色拼点，你获得赢的角色的拼点牌，然后其可以使用你的一张手牌",
  ["#rbj__beiqu-use"] = "北趋：你可以使用 %src 的一张手牌",
  ["@@rbj__shuozu"] = "铄镞",
  ["#rbj__shuozu_filter"] = "铄镞",
}

local yuejin = General(extension, "rbj__yuejin", "wei", 4)
local rbj__qieyun = fk.CreateTriggerSkill{
  name = "rbj__qieyun",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Finish then
      local friends = {}
      player.room.logic:getActualDamageEvents(1, function(e)
        local damage = e.data[1]
        if damage.from and damage.from.role[1] == player.role[1] then
          table.insertIfNeed(friends, damage.from)
        end
      end, Player.HistoryRound)
      if #friends == 1 and not friends[1].dead then
        self.cost_data = friends[1].id
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, nil, "#rbj__qieyun-invoke::"..self.cost_data) then
      self.cost_data = {tos = {self.cost_data}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    local cards = to:drawCards(2, self.name)
    if to == player and not player.dead then
      cards = table.filter(cards, function (id)
        return table.contains(player:getCardIds("h"), id)
      end)
      if #cards > 0 then
        U.askForUseRealCard(room, player, cards, nil, self.name,
          "#rbj__qieyun-use", {bypass_times = true, extraUse = true}, false, true)
      end
    end
  end,
}
yuejin:addSkill(rbj__qieyun)
Fk:loadTranslationTable{
  ["rbj__yuejin"] = "乐进",
  ["#rbj__yuejin"] = "鏖狻陷刀崚",
  ["designer:rbj__yuejin"] = "三秋",
  ["illustrator:rbj__yuejin"] = "小北风巧绘",

  ["rbj__qieyun"] = "挈云",
  [":rbj__qieyun"] = "结束阶段，你可以令友方本轮唯一造成过伤害的角色摸两张牌，若为你，你可以使用其中一张牌。",
  ["#rbj__qieyun-invoke"] = "挈云：是否令 %dest 摸两张牌？",
  ["#rbj__qieyun-use"] = "挈云：你可以使用其中一张牌",
}

local lvbu = General(extension, "rbj__lvbu", "qun", 4)
local rbj__linwu = fk.CreateTriggerSkill{
  name = "rbj__linwu",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  prompt="rbj__linwu-ask",
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Play then
     
        return true
      
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards={}
    for _, p in ipairs(room.alive_players) do
      if not p:isAllNude() then
        local id = room:askForCardChosen(player, p, "hej", self.name)
        --room:obtainCard(player, id, false, fk.ReasonPrey)
        table.insert(cards,id)
        if player.dead then return false end
      end
    end
    if #cards==0 then return end
    local _, dat = player.room:askForUseViewAsSkill(target,  "rbj__linwu_vs", "#rbj__linwu_vs", true)
    local card = Fk:cloneCard("duel")
    card:addSubcards(cards)
    card.skillName = "rbj__linwu"
    room:useCard {
      from = player.id,
      tos = table.map(dat.targets, function(p) return { p } end),
      card = card,
    }

  end,
}

local rbj__linwu_vs = fk.CreateViewAsSkill {
  name = "rbj__linwu_vs",
  card_filter = function(self, to_select, selected)
    return false
  end,
  view_as = function(self, cards)
    --if #cards ~= 2 then return end
    local card = Fk:cloneCard("duel")
    card.skillName = "rbj__linwu"
    return card
  end,
}
Fk:addSkill(rbj__linwu_vs)
lvbu:addSkill(rbj__linwu)
Fk:loadTranslationTable{
  ["rbj__lvbu"] = "吕布",
  ["#rbj__lvbu"] = "武开穹巅",
  ["designer:rbj__lvbu"] = "三秋",
  ["illustrator:rbj__lvbu"] = "鱼仔",

  ["rbj__linwu"] = "凛武",
  [":rbj__linwu"] = "出牌阶段开始时，你可以将所有角色各一张牌当一张【决斗】使用，且你与目标均可以用转化底牌响应之。",
  ["rbj__linwu-ask"]="凛武:你可以将所有角色各一张牌当一张【决斗】使用",
  ["#rbj__linwu_vs"]="你可以对一名角色使用【决斗】！",
}

local guohuai = General(extension, "rbj__guohuai", "wei", 4)
local rbj__xuzhen = fk.CreateTriggerSkill{
  name = "rbj__xuzhen",
  anim_type = "control",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and not target.dead and #target:getCardIds("e") > 0
  end,
  on_cost = function (self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, nil, "#rbj__xuzhen-invoke::"..target.id) then
      self.cost_data = {tos = {target.id}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = room:askForCardChosen(player, target, "e", self.name, "#rbj__xuzhen-choose::"..target.id)
    if target:getHandcardNum() < 2 or
      room:askForSkillInvoke(target, self.name, nil, "#rbj__xuzhen-choice:"..player.id..":"..Fk:getCardById(card):toLogString()) then
      room:throwCard(card, self.name, target, player)
    else
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, true, target.id)
      if target.dead or target:getHandcardNum() < 2 then return end
      local cards = room:askForCard(target, 2, 2, false, self.name, false, nil, "#rbj__xuzhen-recast")
      room:recastCard(cards, target, self.name)
    end
  end,
}
guohuai:addSkill(rbj__xuzhen)
Fk:loadTranslationTable{
  ["rbj__guohuai"] = "郭淮",
  ["#rbj__guohuai"] = "挟锋崛变",
  ["designer:rbj__guohuai"] = "三秋",
  ["illustrator:rbj__guohuai"] = "游漫美绘",

  ["rbj__xuzhen"] = "虚阵",
  [":rbj__xuzhen"] = "当一名角色成为【杀】的目标后，你可以选择其装备区一张牌，其选择一项：1.你弃置此牌；2.将此牌交给你，然后其重铸两张手牌。",
  ["#rbj__xuzhen-invoke"] = "虚阵：你可以选择 %dest 装备区的一张牌，其选择令你弃置之，或交给你然后其重铸两张手牌",
  ["#rbj__xuzhen-choose"] = "虚阵：选择 %dest 装备区的一张牌",
  ["#rbj__xuzhen-choice"] = "虚阵：点“确定” %src 弃置你的%arg；或点“取消”将之交给其，你重铸两张手牌",
  ["#rbj__xuzhen-recast"] = "虚阵：请重铸两张手牌",
}

local caoxiu = General(extension, "rbj__caoxiu", "wei", 4)
local rbj__huochi = fk.CreateTriggerSkill{
  name = "rbj__huochi",
  anim_type = "control",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and (data.card.type == Card.TypeBasic or
      table.contains(player:getTableMark("@rbj__huochi-turn"), data.card:getTypeString().."_char")) and
      table.find(player.room:getOtherPlayers(player), function (p)
        return player:distanceTo(p) == player:getAttackRange() and not p:isNude()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player), function (p)
      return player:distanceTo(p) == player:getAttackRange() and not p:isNude()
    end)
    if room:askForSkillInvoke(player, self.name, nil, "#rbj__huochi-invoke") then
      self.cost_data = {tos = table.map(targets, Util.IdMapper)}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:sortPlayersByAction(self.cost_data.tos)
    local types = {}
    for _, id in ipairs(self.cost_data.tos) do
      if player.dead then return end
      local p = room:getPlayerById(id)
      if not p.dead and not p:isNude() then
        local card = room:askForCardChosen(player, p, "he", self.name, "#rbj__huochi-discard::"..p.id)
        table.insertIfNeed(types, Fk:getCardById(card):getTypeString().."_char")
        room:throwCard(card, self.name, p, player)
      end
    end
    if not player.dead and #types == 1 and types[1] ~= "basic_char" then
      local mark = player:getTableMark("@rbj__huochi-turn")
      table.insertIfNeed(mark, types[1])
      room:setPlayerMark(player, "@rbj__huochi-turn", mark)
    end
  end,
}
caoxiu:addSkill(rbj__huochi)
Fk:loadTranslationTable{
  ["rbj__caoxiu"] = "曹休",
  ["#rbj__caoxiu"] = "千尘脱骥",
  ["designer:rbj__caoxiu"] = "三秋",
  ["illustrator:rbj__caoxiu"] = "西国红云",

  ["rbj__huochi"] = "火驰",
  [":rbj__huochi"] = "当你使用基本牌后，你可以弃置所有你至其距离等于你攻击范围的角色各一张牌，若这些牌类别均相同，本回合此类别的牌也能触发"..
  "〖火驰〗。",
  ["#rbj__huochi-invoke"] = "火驰：是否弃置所有你攻击范围边缘的角色各一张牌？",
  ["#rbj__huochi-discard"] = "火驰：弃置 %dest 一张牌",
  ["@rbj__huochi-turn"] = "火驰",
}

local xujing = General(extension, "rbj__xujing", "shu", 3)
local rbj__fuban = fk.CreateTriggerSkill{
  name = "rbj__fuban",
  anim_type = "support",
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.to == Player.Discard and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(target, self.name, nil, "#rbj__fuban-invoke:"..player.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(target.id, {player.id})
    player:drawCards(1, self.name)
    if player.dead or player:isKongcheng() then return end
    local cards = player:getCardIds("h")
    local yes = false
    if table.find(cards, function (id)
      return Fk:getCardById(id).type ~= Card.TypeBasic
    end) then
      yes = true
    end
    player:showCards(cards)
    if yes and not target.dead then
      target:skip(Player.Discard)
    end
  end,
}
local rbj__chucai = fk.CreateTriggerSkill{
  name = "rbj__chucai",
  anim_type = "support",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local cards = {}
      for _, move in ipairs(data) do
        if move.to == player.id and move.moveReason == fk.ReasonDraw then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).is_damage_card then
              table.insertIfNeed(cards, info.cardId)
            end
          end
        end
      end
      cards = U.moveCardsHoldingAreaCheck(player.room, cards)
      if #cards > 0 and table.find(player.room:getOtherPlayers(player), function (p)
        return p.role[1] == player.role[1]
      end) then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player), function (p)
      return p.role[1] == player.role[1]
    end)
    local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
      "#rbj__chucai-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to, cards = self.cost_data}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:moveCardTo(self.cost_data.cards, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, false, player.id)
    if not player.dead then
      room:handleAddLoseSkills(player, "-"..self.name, nil, true, false)
    end
    if not to.dead then
      room:handleAddLoseSkills(to, self.name, nil, true, false)
    end
  end,
}
xujing:addSkill(rbj__fuban)
xujing:addSkill(rbj__chucai)
Fk:loadTranslationTable{
  ["rbj__xujing"] = "许靖",
  ["#rbj__xujing"] = "镜覆崖花",
  ["designer:rbj__xujing"] = "三秋",
  ["illustrator:rbj__xujing"] = "匪萌十月",

  ["rbj__fuban"] = "负阪",
  [":rbj__fuban"] = "一名角色的弃牌阶段开始前，其可以令你摸一张牌并展示手牌，若其中有非基本牌，其跳过此阶段。",
  ["rbj__chucai"] = "楚才",
  [":rbj__chucai"] = "当你摸牌获得伤害牌后，你可以将这些牌和此技能交给一名友方角色。",
  ["#rbj__fuban-invoke"] = "负阪：是否令 %src 摸一张牌并展示手牌？若其中有非基本牌，你跳过弃牌阶段",
  ["#rbj__chucai-choose"] = "楚才：你可以将其中的伤害牌和此技能交给一名友方角色",
}

local xurong = General(extension, "rbj__xurong", "qun", 4)
local rbj__lujin = fk.CreateTriggerSkill{
  name = "rbj__lujin",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.firstTarget and
      table.find(AimGroup:getAllTargets(data.tos), function (id)
        local p = player.room:getPlayerById(id)
        return not p.dead and table.every(player.room:getOtherPlayers(p), function (q)
          return q:getLostHp() <= p:getLostHp()
        end)
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(AimGroup:getAllTargets(data.tos), function (id)
      local p = room:getPlayerById(id)
      return not p.dead and table.every(room:getOtherPlayers(p), function (q)
        return q:getLostHp() <= p:getLostHp()
      end)
    end)
    if #targets == 1 then
      if room:askForSkillInvoke(player, self.name, nil, "#rbj__lujin-invoke::"..targets[1]) then
        self.cost_data = {tos = targets}
        return true
      end
    else
      targets = room:askForChoosePlayers(player, targets, 1, 10, "#rbj__lujin-choose", self.name, true)
      if #targets > 0 then
        self.cost_data = {tos = targets}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:sortPlayersByAction(self.cost_data.tos)
    for _, id in ipairs(self.cost_data.tos) do
      local p = room:getPlayerById(id)
      if not p.dead then
        room:damage{
          from = player,
          to = p,
          damage = 1,
          skillName = self.name,
        }
      end
      if not p.dead and not p:isKongcheng() then
        local cards = table.filter(p:getCardIds("he"), function (c)
          return Fk:getCardById(c).trueName == data.card.trueName and not p:prohibitDiscard(id)
        end)
        if #cards > 0 then
          if room:askForSkillInvoke(p, self.name, nil, "#rbj__lujin-discard:::"..data.card.trueName) then
            room:throwCard(cards, self.name, p, p)
            if not p.dead and p:isWounded() then
              room:recover({
                who = p,
                num = math.min(#cards, p:getLostHp()),
                recoverBy = p,
                skillName = self.name,
              })
            end
          end
        else
          room:askForDiscard(p, 1, 1, false, self.name, true, self.name, "#rbj__lujin-discard:::"..data.card.trueName)  --假装询问
        end
      end
    end
  end,
}
xurong:addSkill(rbj__lujin)
Fk:loadTranslationTable{
  ["rbj__xurong"] = "徐荣",
  ["#rbj__xurong"] = "迫陷堕绝",
  ["designer:rbj__xurong"] = "三秋",
  ["illustrator:rbj__xurong"] = "biou09",

  ["rbj__lujin"] = "戮烬",
  [":rbj__lujin"] = "当你使用牌指定第一个目标后，你可以选择目标角色中任意名已损失体力值最多的角色，这些角色依次执行：你对其造成1点伤害，"..
  "然后其可以弃置所有此牌名的牌，回复等量的体力。",
  ["#rbj__lujin-invoke"] = "戮烬：是否对 %dest 造成1点伤害？",
  ["#rbj__lujin-choose"] = "戮烬：你可以对其中任意名角色造成1点伤害",
  ["#rbj__lujin-discard"] = "戮烬：是否弃置所有【%arg】，回复等量体力？",
}

local luxun = General(extension, "rbj__luxun", "wu", 3)
local rbj__dingrui = fk.CreateTriggerSkill{
  name = "rbj__dingrui",
  anim_type = "control",
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.from > Player.Start and data.from < Player.Finish and not player:isKongcheng() and player.hp > 0 and
      player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local phase_name_table = {
      [3] = "phase_judge",
      [4] = "phase_draw",
      [5] = "phase_play",
      [6] = "phase_discard",
    }
    local cards = player.room:askForCard(player, 1, player.hp, false, self.name, true, "slash",
      "#rbj__dingrui-invoke:::"..phase_name_table[data.from]..":"..player.hp)
    if #cards > 0 then
      self.cost_data = {cards = cards}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:recastCard(self.cost_data.cards, player, self.name)
    if  not player.dead then
      player:gainAnExtraPhase(data.from)
    end
  end,
}
local rbj__qingya = fk.CreateTriggerSkill{
  name = "rbj__qingya",
  anim_type = "special",
  frequency = Skill.Compulsory,

  refresh_events = {fk.CardUsing, fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and (event == fk.CardUsing and target == player or event == fk.Deathed)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if #table.filter(room:getOtherPlayers(player), function(p)
      return p.role[1] == player.role[1]
    end) == #room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
      local use = e.data[1]
      if use and use.from == player.id then
        return true
      end
    end, Player.HistoryTurn) then
      room:setPlayerMark(player, "rbj__qingya-turn", 1)
    else
      room:setPlayerMark(player, "rbj__qingya-turn", 0)
    end
    player:filterHandcards()
  end,
}
local rbj__qingya_filter = fk.CreateFilterSkill{
  name = "#rbj__qingya_filter",
  card_filter = function(self, card, player)
    return player:hasSkill(rbj__qingya) and player:getMark("rbj__qingya-turn") > 0 and
      card.type == Card.TypeBasic and table.contains(player:getCardIds("h"), card.id)
  end,
  view_as = function(self, card)
    return Fk:cloneCard("analeptic", card.suit, card.number)
  end,
}
local rbj__qingya_maxcards = fk.CreateMaxCardsSkill{
  name = "#rbj__qingya_maxcards",
  exclude_from = function(self, player, card)
    return player:hasSkill(rbj__qingya) and player:getMark("rbj__qingya-turn") > 0 and
      card.type == Card.TypeBasic
  end,
}
rbj__qingya:addRelatedSkill(rbj__qingya_filter)
rbj__qingya:addRelatedSkill(rbj__qingya_maxcards)
luxun:addSkill(rbj__dingrui)
luxun:addSkill(rbj__qingya)
Fk:loadTranslationTable{
  ["rbj__luxun"] = "陆逊",
  ["#rbj__luxun"] = "剑照儒纶",
  ["designer:rbj__luxun"] = "三秋",
  ["illustrator:rbj__luxun"] = "魔奇士",

  ["rbj__dingrui"] = "定锐",
  [":rbj__dingrui"] = "每回合限一次，当你的阶段结束后（准备阶段和结束阶段除外），你可以重铸体力值张【杀】，再执行一个此阶段。",
  ["rbj__qingya"] = "青崖",
  [":rbj__qingya"] = "锁定技，若你本回合已使用牌数等于友方其他角色数，你手牌中的基本牌视为不计入手牌上限的【酒】。",
  ["#rbj__dingrui-invoke"] = "定锐：你可以重铸至多%arg2张【杀】，再执行一个%arg",
  ["#rbj__qingya_filter"] = "青崖",
}

local fazheng = General(extension, "rbj__fazheng", "shu", 3)
local rbj__jingfen = fk.CreateTriggerSkill{
  name = "rbj__jingfen",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local colors = {}
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard then
          for _, info in ipairs(move.moveInfo) do
            local color = Fk:getCardById(info.cardId).color
            if color ~= Card.NoColor then
              table.insertIfNeed(colors, color)
            end
          end
        end
      end
      return #colors == 2
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if p.role[1] == player.role[1] and p:getMark("rbj__jingfen-round") > 0 then
        room:doIndicate(player.id, {p.id})
        room:setPlayerMark(p, "rbj__jingfen-round", 0)
      end
    end
  end,

  refresh_events = {fk.AfterCardUseDeclared},
  can_refresh = function (self, event, target, player, data)
    return target == player and data.card.trueName == "slash" and player.phase == Player.Play and not data.extraUse and
      table.find(player.room.alive_players, function (p)
        return p:hasSkill(self) and p.role[1] == player.role[1]
      end)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    player:addCardUseHistory("slash", -1)
    local card = Fk:cloneCard("slash")
    for _, p in ipairs(room:getAlivePlayers()) do
      if p.role[1] == player.role[1] and (card.skill:getMaxUseTime(p, Player.HistoryPhase, card, nil) or 0) > 0 then
        room:addPlayerMark(p, "rbj__jingfen-round", 1)
        break
      end
    end
  end,
}
local rbj__jingfen_targetmod = fk.CreateTargetModSkill{
  name = "#rbj__jingfen_targetmod",
  frequency = Skill.Compulsory,
  main_skill = rbj__jingfen,
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
      local n = 0
      if player.phase == Player.Play and
        table.find(Fk:currentRoom().alive_players, function (p)
          return p:hasSkill(rbj__jingfen) and p.role[1] == player.role[1]
        end) then
        for _, p in ipairs(Fk:currentRoom().alive_players) do
          if p ~= player and p.role[1] == player.role[1] then
            local card = Fk:cloneCard("slash")
            n = n + (card.skill:getMaxUseTime(p, Player.HistoryPhase, card, nil) or 0)
          end
        end
      end
      n = n - player:getMark("rbj__jingfen-round")
      return n
    end
  end,
}
local rbj__zhanye = fk.CreateTriggerSkill{
  name = "rbj__zhanye",
  anim_type = "drawcard",
  events = {fk.Damage, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target and target == player and player:hasSkill(self) and not player:isKongcheng() and
      data.card and player.room:getCardArea(data.card) == Card.Processing
  end,
  on_cost = function (self, event, target, player, data)
    local n = (player:getHandcardNum() + 1) // 2
    local cards = player.room:askForDiscard(player, n, n, false, self.name, true, nil, "#rbj__zhanye-invoke:::"..n, true)
    if #cards > 0 then
      self.cost_data = {cards = cards}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if player.dead then return end
    if data.card and room:getCardArea(data.card) == Card.Processing then
      room:moveCardTo(data.card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id, "@@rbj__zhanye-inhand")
    end
  end,
}
local rbj__zhanye_delay = fk.CreateTriggerSkill{
  name = "#rbj__zhanye_delay",
  mute = true,
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player:usedSkillTimes("rbj__zhanye", Player.HistoryTurn) > 0 and table.find(player:getCardIds("h"), function(id)
      return Fk:getCardById(id):getMark("@@rbj__zhanye-inhand") > 0
    end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("rbj__zhanye")
    room:notifySkillInvoked(player, "rbj__zhanye", "drawcard")
    while not player.dead do
      local cards = table.filter(player:getCardIds("h"), function(id)
        return Fk:getCardById(id):getMark("@@rbj__zhanye-inhand") > 0
      end)
      if #cards == 0 then return end
      room:delay(800)
      if not room:useVirtualCard("ex_nihilo", {cards[1]}, player, player, "rbj__zhanye") then
        room:setCardMark(Fk:getCardById(cards[1]), "@@rbj__zhanye-inhand", 0)
      end
    end
  end,
}
rbj__jingfen:addRelatedSkill(rbj__jingfen_targetmod)
rbj__zhanye:addRelatedSkill(rbj__zhanye_delay)
fazheng:addSkill(rbj__jingfen)
fazheng:addSkill(rbj__zhanye)
Fk:loadTranslationTable{
  ["rbj__fazheng"] = "法正",
  ["#rbj__fazheng"] = "身睚功眦",
  ["designer:rbj__fazheng"] = "三秋",
  ["illustrator:rbj__fazheng"] = "",

  ["rbj__jingfen"] = "旌分",
  [":rbj__jingfen"] = "锁定技，友方角色共享出牌阶段使用【杀】次数；当你一次弃置两种颜色的牌后，所有友方角色恢复以此法减少的次数上限。<br>"..
  "<font color='grey'>#\"<b>共享次数</b>\"：使用【杀】次数上限增加其他友方角色（不以此法增加的）次数上限之和，当声明使用计入次数限制的"..
  "【杀】后，改为按行动顺序令一名友方角色本轮出牌阶段使用【杀】次数上限-1，每轮结束后恢复以此法减少的次数上限。",
  ["rbj__zhanye"] = "斩业",
  [":rbj__zhanye"] = "当你造成或受到伤害后，你可以弃置一半手牌（向上取整）并获得造成伤害的牌，若如此做，本回合结束时，你将手牌中本回合因此"..
  "获得的牌依次当【无中生有】使用。",
  ["#rbj__zhanye-invoke"] = "斩业：你可以弃置一半手牌（%arg张），获得造成伤害的牌",
  ["@@rbj__zhanye-inhand"] = "斩业",
  ["#rbj__zhanye_delay"] = "斩业",
}

local luotong = General(extension, "rbj__luotong", "wu", 3)

local rbj__shupu = fk.CreateTriggerSkill{
  name = "rbj__shupu",
  anim_type = "drawcard",
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.to == Player.Draw and not player.skipped_phases[Player.Play] and
      player:getMark("@@rbj__shupu") == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#rbj__shupu-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:skip(Player.Draw)
    player:skip(Player.Play)
    local friends = table.filter(room.alive_players, function (p)
      return p.role[1] == player.role[1]
    end)
    if #friends == 1 then
      player:drawCards(5, self.name)
      if not player.dead then
        room:setPlayerMark(player, "@@rbj__shupu", 1)
        room:setPlayerMark(player, "rbj__shupu_targets", {player.id})
      end
    else
      local total = 5
      while total > 0 do
        room:setPlayerMark(player, "rbj__shupu-tmp", total)
        local _, dat = room:askForUseActiveSkill(player, "rbj__shupu_active",
          "#rbj__shupu-num:::"..total, false, {exclusive_targets = table.map(friends, Util.IdMapper)})
        local to = room:getPlayerById(dat.targets[1])
        room:addPlayerMark(to, "@rbj__shupu_count", dat.interaction)
        total = total - dat.interaction
      end
      local n = 0
      for _, p in ipairs(friends) do
        n = math.max(n, p:getMark("@rbj__shupu_count"))
      end
      local rbj__shupu_targets = {}
      for _, p in ipairs(room:getAlivePlayers()) do
        if p:getMark("@rbj__shupu_count") > 0 then
          if p:getMark("@rbj__shupu_count") == n then
            table.insert(rbj__shupu_targets, p.id)
          end
          p:drawCards(p:getMark("@rbj__shupu_count"), self.name)
          room:setPlayerMark(p, "@rbj__shupu_count", 0)
        end
      end
      if not player.dead and table.find(rbj__shupu_targets, function (id)
        return not room:getPlayerById(id).dead
      end) then
        room:setPlayerMark(player, "@@rbj__shupu", 1)
        room:setPlayerMark(player, "rbj__shupu_targets", rbj__shupu_targets)
      end
    end
  end,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if player:getMark("rbj__shupu_targets") ~= 0 then
      for _, move in ipairs(data) do
        if move.from and player.room:getPlayerById(move.from):isKongcheng() and
          table.contains(player:getMark("rbj__shupu_targets"), move.from) then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand then
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@rbj__shupu", 0)
    room:setPlayerMark(player, "rbj__shupu_targets", 0)
  end,
}
local rbj__shupu_active = fk.CreateActiveSkill{
  name = "rbj__shupu_active",
  card_num = 0,
  target_num = 1,
  interaction = function()
    return UI.Spin {
      from = 1,
      to = Self:getMark("rbj__shupu-tmp"),
    }
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected)
    return #selected == 0
  end,
}
local rbj__jize = fk.CreateTriggerSkill{
  name = "rbj__jize",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and #player.room.alive_players > 1 and
      table.find(player.room.alive_players, function (p)
        return not p:isKongcheng()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "rbj__jize_active", "#rbj__jize-invoke", true, nil, true)
    if success and dat then
      self.cost_data = {tos = {dat.targets[1]}, extra_data = dat.targets[2]}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local target1 = room:getPlayerById(self.cost_data.tos[1])
    local target2 = room:getPlayerById(self.cost_data.extra_data)
    room:doIndicate(target1.id, {target2.id})
    local card
    if target1 == player then
      card = room:askForCard(player, 1, 1, false, self.name, false, nil, "#rbj__jize-give::"..target2.id)
    else
      card = room:askForCardChosen(player, target1, "h", self.name, "#rbj__jize-card:"..target1.id..":"..target2.id)
    end
    room:moveCardTo(card, Card.PlayerHand, target2, fk.ReasonGive, self.name, nil, false, player.id)
    if player.dead or not player:isWounded() then return end
    local nums = {}
    for _, p in ipairs(room.alive_players) do
      nums[p:getHandcardNum()] = (nums[p:getHandcardNum()] or 0) + 1
    end
    local yes = false
    for _, count in pairs(nums) do
      if count > 1 then
        if yes == false then
          yes = true
        else
          return
        end
      end
    end
    if yes then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      })
    end
  end,
}
local rbj__jize_active = fk.CreateActiveSkill{
  name = "rbj__jize_active",
  card_num = 0,
  target_num = 2,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected)
    if #selected == 0 then
      return not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
    else
      return true
    end
  end,
}
Fk:addSkill(rbj__shupu_active)
Fk:addSkill(rbj__jize_active)
luotong:addSkill(rbj__shupu)
luotong:addSkill(rbj__jize)
Fk:loadTranslationTable{
  ["rbj__luotong"] = "骆统",
  ["#rbj__luotong"] = "施善绥安",
  ["designer:rbj__luotong"] = "三秋",
  ["illustrator:rbj__luotong"] = "鬼画府",

  ["rbj__shupu"] = "疏浦",
  [":rbj__shupu"] = "你可以跳过摸牌和出牌阶段，令友方角色摸共计五张牌，然后此技能失效直到因此摸牌最多的角色失去最后的手牌。",
  ["rbj__jize"] = "及泽",
  [":rbj__jize"] = "当你受到伤害后，你可以将一名角色的一张手牌交给另一名角色，然后若存活角色的手牌数中仅有一种有多名角色为此手牌数，"..
  "你回复1点体力。",
  ["@@rbj__shupu"] = "疏浦失效",
  ["#rbj__shupu-invoke"] = "疏浦：是否跳过摸牌和出牌阶段，令友方角色摸共计五张牌？",
  ["#rbj__shupu-num"] = "疏浦：为友方角色分配摸牌数（还剩%arg张）",
  ["@rbj__shupu_count"] = "疏浦摸牌数",
  ["rbj__shupu_active"] = "疏浦",
  ["#rbj__jize-invoke"] = "及泽：你可以选择一名角色，将其一张手牌交给另一名角色",
  ["rbj__jize_active"] = "及泽",
  ["#rbj__jize-give"] = "及泽：选择一张手牌交给 %dest",
  ["#rbj__jize-card"] = "及泽：选择 %src 的一张手牌交给 %dest",
}

return extension
